//
//  GoogleHealth.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 3/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "GoogleHealth.h"


@implementation GoogleHealth
@synthesize mProfileFeed, mProfileListFeed, mRegisterFeed;
@synthesize gUsername, gPassword, profileName, profileID;
@synthesize isRegisterFeedPending;
@synthesize mServiceClass;

#pragma mark -
#pragma mark Google Health methods
-(id)init
{
    if (self = [super init])
    {
		// initialize private variables?
    }
    return self;
}

-(void) useGoogleHealthProduction: (BOOL) option 
{
	if(option == YES) 
		mServiceClass = [GDataServiceGoogleHealth class];
	else {
		mServiceClass = [GDataServiceGoogleHealthSandbox class];
	}

}

- (GDataServiceGoogleHealth *) healthService 
{
	static GDataServiceGoogleHealth *service = nil;
	
	// the service class may have changed if the user clicked the sandbox
	// radio buttons
	if (service == nil || ![service isMemberOfClass:mServiceClass]) {
		
		// allocate the currently-selected service class
		[service release];
		service = [[mServiceClass alloc] init];
		
		[service setUserAgent:@"JHU-iHealthEHR-1.0"]; // set this to yourName-appName-appVersion
		
		[service setShouldCacheDatedData:YES];
		//[service setServiceShouldFollowNextLinks:YES];
		
		// iPhone apps will typically disable caching dated data or will call
		// clearLastModifiedDates after done fetching to avoid wasting
		// memory.
	}
	
	// username/password may change
	// NSLog(@"username = %@", gUsername);
	[service setUserCredentialsWithUsername:gUsername
								   password:gPassword];
	
	
	return service;
}

-(void)fetchMyFeeds:(NSString *) profile withDelegate:(id) delegate andCallback:(SEL) function {
	
	// self.mProfileListFeed = nil;
	if(profileName != nil)
		[profileName release];
	profileName = [[NSString alloc] initWithString:profile];	
	callerDelegate = delegate;
	// callerFunction = function;
	GDataServiceGoogleHealth *service = [self healthService];
	NSURL *feedURL = [self getFeedURL];
	[service fetchFeedWithURL:feedURL
					 delegate:self
			didFinishSelector:@selector(profileListFeedTicket:finishedWithFeed:error:)]; 	
}

-(void) profileListFeedTicket:(GDataServiceTicket *) ticket
             finishedWithFeed:(GDataFeedBase *) feed
                        error:(NSError *) error 
{	
	if(error == nil) {
		if(self.mProfileListFeed != nil)
			[self.mProfileListFeed release];
		self.mProfileListFeed = [feed retain];		
		// should be a private variable?
		GDataEntryBase *entry = [self selectProfile:profileName];
		
		/*if(entry == nil) {			
			[callerDelegate loginFailed:nil stage:@"profileListFeed"];
		}*/
		
		profileID = [[entry content] stringValue];		
		GDataServiceGoogleHealth *service = [self healthService];
		
		NSURL *feedURL;
		//		if ([self isProfileSegmentSelected]) {
		// fetch a profile feed
		feedURL = [mServiceClass profileFeedURLForProfileID:profileID];
		[service fetchFeedWithURL:feedURL
						 delegate:self
				didFinishSelector:@selector(profileFeedTicket:finishedWithFeed:error:)];		
		NSLog(@"Loaded entry with profileName '%@' with ID:'%@'", profileName, profileID);		 
	}
	else {
		NSLog(@"Login failed!");
		[callerDelegate loginFailed:error stage:@"profileListFeed"];
	}
}

- (void)profileFeedTicket:(GDataServiceTicket *)ticket
         finishedWithFeed:(GDataFeedHealthProfile *)feed
                    error:(NSError *)error {
	if(error == nil) {
		if(self.mProfileFeed != nil) 
			[self.mProfileFeed release];
		self.mProfileFeed = [feed retain];
		// NSLog(@"mProfileFeed set: %@\n", [self.mProfileFeed description]);
			
		GDataServiceGoogleHealth *service = [self healthService];
		NSURL *feedURL = [mServiceClass registerFeedURLForProfileID:profileID];
		[service fetchFeedWithURL:feedURL
						 delegate:self
				didFinishSelector:@selector(registerFeedTicket:finishedWithFeed:error:)];			
	}
	else {
		NSLog(@"ERROR: cannot retrieve profile => %@", error);
		// display UIAlert if login fails.
		[callerDelegate loginFailed:error stage:@"profileFeed"];
	}
}

- (void)registerFeedTicket:(GDataServiceTicket *)ticket
		  finishedWithFeed:(GDataFeedHealthRegister *)feed
					 error:(NSError *)error {
	if(error == nil) {
		// NSLog(@"We got some notices?");
		if(self.mRegisterFeed != nil) 
			[self.mRegisterFeed release];
		self.mRegisterFeed = [feed retain];
		
		[callerDelegate loginSuccessfulandFeedsSet];
	}
	else {
		NSLog(@"Error while retreving notices: %@", [error description]);
		[callerDelegate loginFailed:error stage:@"registerFeed"];
	}
}

-(GDataEntryBase *) selectProfile:(NSString *) name
{
	if(self.mProfileListFeed == nil) {
		return nil;
	}
	/* now pull specific profile and register here */
	GDataEntryBase *entry;
	NSString *item;
	for(int i = 0; i < [[self.mProfileListFeed entries] count]; i++) {
		entry = [[self.mProfileListFeed entries] objectAtIndex:i];
		item = [[entry title] stringValue];
		NSLog(@"feed items: %@ == %@", item, name);
		if([item isEqualToString:profileName]) {
			return entry;
		}
	}
	/* could not find a profile with that name */
	return nil;
}

-(NSURL *)getFeedURL
{
	return [mServiceClass profileListFeedURL];
}

-(void) sendUpdate:(GDataContinuityOfCareRecord *) ccrEntry withDelegate:(id) delegate andCallback:(SEL) function
{
	GDataServiceGoogleHealth *service = [self healthService];
	GDataEntryHealthProfile *newProfileEntry = [GDataEntryHealthProfile 
												profileEntry]; 
	[newProfileEntry setContinuityOfCareRecord:ccrEntry]; 
	
	if(self.mProfileFeed != nil) {
		// insert the new entry into the profile feed 
		NSURL *postURL = [[self.mProfileFeed postLink] URL]; 
		// NSLog(@"Post profile update to => %@", [postURL absoluteString]);
		[service fetchEntryByInsertingEntry:newProfileEntry 
								 forFeedURL:postURL 
								   delegate:self 
						  didFinishSelector:@selector(postTicket:finishedWithEntry:error:)]; 
	}
}

- (void) postTicket:(GDataServiceTicket *)ticket
  finishedWithEntry:(GDataEntryHealthProfile *)feed
			  error:(NSError *)error {
	NSString *message;
	// NSString *mytitle = @"Upload";
	if(error == nil) {
		message = @"Successfully uploaded entry!";		
		NSLog(@"Msg => '%@'", message);
		[callerDelegate uploadSuccessful];
	}
	else {
		message = @"Failed to upload entries!";
		[callerDelegate uploadFailed:error stage:@"Upload"];
	}
	/*	UIAlertView *status = [[UIAlertView alloc] initWithTitle:mytitle message:message
	 delegate:self cancelButtonTitle:nil 
	 otherButtonTitles:@"OK", nil];
	 [status show];
	 [status release];	*/
}


-(void) sendNotice:(NSString *) noticeTitle withContent:(NSString *) contentHtml
{
	GDataServiceGoogleHealth *service = [self healthService]; 
	
	if(self.mRegisterFeed != nil) {
		GDataEntryHealthRegister *newRegisterEntry = [GDataEntryHealthRegister registerEntry];
		
		NSURL *noticeURL = [[self.mRegisterFeed postLink] URL];
		// NSLog(@"Post notice update to => %@", [noticeURL absoluteString]);
		
		[newRegisterEntry setTitleWithString:noticeTitle];
		[newRegisterEntry setContentWithString:contentHtml];
		 
		[service fetchEntryByInsertingEntry:newRegisterEntry 
								  forFeedURL:noticeURL 
									delegate:self 
						   didFinishSelector:@selector(postNotice:finishedWithEntry:error:)]; 
	}
}		 

- (void) postNotice:(GDataServiceTicket *)ticket
						   finishedWithEntry:(GDataEntryHealthRegister *)feed
									   error:(NSError *)error {
	NSString *message;
	NSString *mytitle = @"Notice";
	if(error == nil) {
	   message = @"Successfully sent notice!";
    }
    else {
	   message = @"Failed send notice!";
    }
    UIAlertView *status = [[UIAlertView alloc] initWithTitle:mytitle message:message
													delegate:self cancelButtonTitle:nil 
											otherButtonTitles:@"OK", nil];
	[status show];
	[status release];									   
}
		 
		 
- (void)dealloc {
	[gUsername release];
	[gPassword release];
	[mProfileFeed release];
	[mProfileListFeed release];
	[mRegisterFeed release];
	[mServiceClass release];
// private variable release
	[callerDelegate release];
	[profileName release];
	[profileID release];
    [super dealloc];
}

@end
